new Vue({
  el: "#app",
  data() {
    return {
      nodeKey: "",
      Model_Name: "",
      titlw: "", //添加页面类型
      type: "", //添加页面类型
      form: {
        Parent_Number: "", //父模块编号
        Level: "", //模块级别
        Order: "", //菜单顺序
        Path: "", //存盘路径
        Url: "", //web访问路径
        Icon: "", //图标
        Model_Name: "", //菜单名称
        Admin_Type: "0",
        Parent: [],
      },
      Icon: [], //图标库
      rules: {
        //表单验证规则
        // Model_Name: [
        //   { required: true, message: "请输入菜单名称", trigger: "blur" },
        // ],
        Order: [{ required: true, message: "请输入菜单顺序", trigger: "blur" }],
        // Icon: [
        //   { required: true, message: "请选择菜单图标", trigger: "change" },
        // ],
      },
      relativePath: '',
      loading: false,
      visibleDialog: false,
      Components_Name: "", //查询输入框
      rawData: [], // 新增：存储原始扁平数据
      filteredData: [], // 新增：存储过滤后的数据
      defaultProps: {
        children: "children",
        label: "Model_Name",
      },
      tableData: [],
      treeData: [],
      nodeEditData: {}, //修改
      page: [],
      cloneTreeData: [],
    };
  },

  mounted() {
    let ls_URL = window.location.href;
    this.relativePath = ls_URL.substring(
      ls_URL.lastIndexOf("view"),
      ls_URL.length
    );
    this.getData();
    this.geticon();
  },
  methods: {
    check() {
      this.cloneTreeData = JSON.parse(JSON.stringify(this.treeData));
      let lArray_TreeData = this.cloneTreeData;
      this.tableData = this.Recursion(lArray_TreeData);
    },
    Recursion(lArray_TreeData) {
      // 创建一个副本，避免在遍历时修改原数组
      const result = [];
      for (let i = 0; i < lArray_TreeData.length; i++) {
        const lJSONObject_Record = lArray_TreeData[i];
        const lJSONArray_Children = lJSONObject_Record.children || [];
        // 递归处理子节点
        const filteredChildren = this.Recursion(lJSONArray_Children);
        // 如果当前节点名称匹配搜索条件，或者有匹配的子节点，则保留
        const nameMatch = lJSONObject_Record.Model_Name.includes(
          this.Model_Name
        );
        const hasChildren = filteredChildren.length > 0;
        if (nameMatch || hasChildren) {
          // 创建一个新对象，避免修改原数据
          const newNode = { ...lJSONObject_Record };
          newNode.children = filteredChildren;
          result.push(newNode);
        }
      }
      return result;
    },
    //获取页面数据
    getData() {
      console.log(11);
      const _this = this;
      // $.ajax({
      //   headers: requestHeaders(),
      //   url: `${mh}/generalBusiness/generalQueryBySQLSerialNumberWithOriginal`,
      //   type: "POST",
      //   data: {
      //     SQLSerialNumber: "s_base_system_model_list",
      //     Condition: window.btoa(unescape(encodeURIComponent("%%"))),
      //   },
      //   success: function (data) {
      //       _this.rawData = data; // 存储原始数据
      //       _this.filteredData = data; // 初始化过滤数
      //   },
      //   complete: (XMLHttpRequest) => {
      //     requestPretreatment(XMLHttpRequest);
      //   },
      //   dataType: "json",
      // });
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/getMenuList`,
        type: "GET",
        success: function (data) {
          console.log(JSON.stringify(data) );
          _this.tableData = data;
          _this.treeData = data;
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    // 树形结构构建方法（优化版）
    buildTree(data) {
      if (!Array.isArray(data)) return [];

      const map = {};
      const tree = [];
      const clonedData = JSON.parse(JSON.stringify(data));

      // 创建映射
      clonedData.forEach((node) => {
        map[node.Model_Number] = { ...node, Children: [] };
      });

      // 构建树结构
      clonedData.forEach((node) => {
        const parent = map[node.Parent_Number];
        if (parent) {
          parent.Children.push(map[node.Model_Number]);
        } else {
          tree.push(map[node.Model_Number]);
        }
      });

      return this.filterEmptyNodes(tree);
    },
    // 过滤空子节点（辅助方法）
    filterEmptyNodes(nodes) {
      return nodes.filter((node) => {
        if (node.Children.length > 0) {
          node.Children = this.filterEmptyNodes(node.Children);
        }
        return (
          node.Model_Name.toLowerCase().includes(
            this.Components_Name.toLowerCase()
          ) || node.Children.length > 0
        );
      });
    },
    config(row) {
      sessionStorage.setItem("Url", row.Url);
      window.location.href = "../tool/sql/sql_config.html?action=Add";
    },
    configedit(row) {
      sessionStorage.setItem("Url", row.Url);
      window.location.href =
        "../tool/sql/sql_config.html?action=Modify&nodeKey=" +
        row.SQL_SerialNumber;
    },
    // 添加菜单
    Add(node, data) {
      this.titlw = "addF";
      this.type = "addF";
      this.visibleDialog = true;
    },
    // 添加子菜单
    Addc(node, data) {
      console.log(node, data);
      console.log(data.Model_Number);
      this.form = {
        Parent_Number: "", //父模块编号
        Level: "", //模块级别
        Order: "", //菜单顺序
        Path: "", //存盘路径
        Url: "", //web访问路径
        Icon: "", //图标
        Model_Name: "", //菜单名称
        Admin_Type: "0",
        Parent: [],
      };
      this.form.Parent_Number = data.Model_Number;
      this.form.Parent = this.configValue(
        this.tableData,
        data.Model_Number
      )
      this.type = "addC";
      this.titlw = "add";
      this.visibleDialog = true;
    },
    changecaidan(val){
      if (val) {
        this.form.Level = val.length + 1;
        console.log();
      }
    },
    //菜单图标
    geticon() {
      const _this = this;
      $.ajax({
        url: "../../api/Icon.json",
        type: "GET",
        success: function (data) {
          _this.Icon = data;
        },
      });
      // $.ajax({
      //   url: "../../component/pear/font/iconfont.json",
      //   type: "GET",
      //   success: function (res) {
      //     console.log(res.glyphs.map(i=>'pear-icon-' + i.font_class));
      //     _this.Icon = res.glyphs.map(i=>'pear-icon-' + i.font_class);
      //   },
      // });
    },
    //提交页面信息
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        console.log(valid);
        if (valid) {
          if (this.type == "addF") {
            this.form.Level = 1;
          }
          this.form.Parent_Number = this.form.Parent && this.form.Parent.length > 0 ? this.form.Parent[this.form.Parent.length - 1] : "";
          console.log(this.form);
          let lArray = new Array();
          lArray.push(this.form);
          let lJSONObject_base_system_model_list = new Object();
          lJSONObject_base_system_model_list.base_system_model_list = lArray; //换表
          let lJSONObject_DataSet = new Object(); // Modify
          console.log(this.titlw);
          if (this.titlw == "mo") {
            lJSONObject_DataSet.Modify = lJSONObject_base_system_model_list; //换表
            this.sub(lJSONObject_DataSet);
          } else {
            lJSONObject_DataSet.Add = lJSONObject_base_system_model_list; //换表
            const _this = this;
            $.ajax({
              headers: requestHeaders(),
              url: `${mh}/clientOperation/generalSaveForClient`,
              type: "POST",
              data: {
                Data: JSON.stringify(lJSONObject_DataSet),
              },
              success: function (res) {
                console.log(res);
                // return;
                let obform = new Object();
                obform.Model_Number = res.Data;
                obform.User_Number = "Admin";
                obform.UR_Page = "1111";
                obform.UR_New = "1";
                obform.UR_Del = "1";
                obform.UR_Modify = "1";
                obform.UR_Query = "1";
                console.log(obform);
                let lArray = new Array();
                lArray.push(obform);
                let lJSONObject_base_system_rights_user_model = new Object();
                lJSONObject_base_system_rights_user_model.base_system_rights_user_model =
                  lArray; //换表
                let lJSONObject_DataSet2 = new Object(); // Modify
                lJSONObject_DataSet2.Add =
                  lJSONObject_base_system_rights_user_model; //换表
                _this.sub(lJSONObject_DataSet2);
              },
              complete: (XMLHttpRequest) => {
                requestPretreatment(XMLHttpRequest);
              },
            });
          }
        }
      });
    },
    sub(sub) {
      const _this = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/clientOperation/generalSaveForClient`,
        type: "POST",
        data: {
          Data: JSON.stringify(sub),
        },
        success: function (res) {
          console.log(res);
          _this.visibleDialog = false;
          _this.form = {};
          _this.getData();
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    //编辑按钮
    Edit(node, row) {
      this.titlw = "mo";
      this.visibleDialog = true;
      if (row.Level == 1) {
        this.type = "addF";
      } else {
        this.type = "addC";
      }
      console.log(node, row);
      const _this = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryBySQLSerialNumberWithOriginal`,
        type: "POST",
        data: {
          SQLSerialNumber: "s_base_system_model_list",
          Condition: window.btoa(
            unescape(encodeURIComponent("%" + row.Model_Number + "%"))
          ),
        },
        success: function (data) {
          data[0].Parent = _this.configValue(
            _this.tableData,
            data[0].Parent_Number
          );
          _this.form = data[0];
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    configValue(options, val) {
      for (let i = 0; i < options.length; i++) {
        const item = options[i];
        if (item["Model_Number"] == val) {
          return [item["Model_Number"]];
        } else if (item["children"] && item["children"].length > 0) {
          let arr = this.configValue(item["children"], val);
          if (arr) {
            return [item["Model_Number"], ...arr];
          }
        }
      }
    },
    Remove(node, row) {
      console.log(node);
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
        method: "post",
        data: {
          Data: 'base_system_model_list',
          Condition: `Model_Number='${node.Model_Number}'`,
        },
        success: (data) => {
          data[0].Row_Status = '1';
          let lJSONObject_DataSet = {
            Modify: {
              base_system_model_list: data
            }
          }
          let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
          lJSONObject_DataSet['Add'] = new Object();
          lJSONObject_DataSet['Add']['base_operation_log'] = [{
            Operation_Type: '0',
            Operation_Path: this.relativePath,
            Operation_Main,
            Operation_Interface: "generalSaveByRequestBody",
            Operation_IP: getIpAddress()
          }]
          console.log(lJSONObject_DataSet);
          submitSave(lJSONObject_DataSet, (res) => {
            if (res.Status == 'success') {
              this.getData();
              this.visibleDialog = false;
            } else {
              this.$message({
                type: 'error',
                message: '删除失败'
              });
            }
          })
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest)
        },
      });

      // delete node.Children;
      // node.Row_Status = "1";
      // console.log(node, row);
      // let lArray = new Array();
      // lArray.push(node);
      // let lJSONObject_base_system_model_list = new Object();
      // lJSONObject_base_system_model_list.base_system_model_list = lArray; //换表
      // let lJSONObject_DataSet = new Object(); // Modify
      // lJSONObject_DataSet.Modify = lJSONObject_base_system_model_list; //换表
      // console.log(lJSONObject_DataSet);
      // //   return;
      // const _this = this;

      // $.ajax({
      //   headers: requestHeaders(),
      //   url: `${mh}/clientOperation/generalSaveForClient`,
      //   type: "POST",
      //   data: {
      //     Data: JSON.stringify(lJSONObject_DataSet),
      //   },
      //   success: function (res) {
      //     console.log(res);
      //     _this.getData();
      //     _this.visibleDialog = false;
      //   },
      //   complete: (XMLHttpRequest) => {
      //     requestPretreatment(XMLHttpRequest);
      //   },
      //   dataType: "json",
      // });
    },
    //查询按钮
    // 查询方法（实现过滤功能）
    onSerach() {
      const searchText = this.Components_Name.trim().toLowerCase();

      if (!searchText) {
        // 恢复完整数据
        this.filteredData = [...this.rawData];
        this.tableData = this.buildTree(this.rawData);
        return;
      }

      // 执行过滤
      this.filteredData = this.rawData.filter((item) =>
        item.Model_Name.toLowerCase().includes(searchText)
      );

      // 构建过滤后的树结构
      this.tableData = this.buildTree(this.filteredData);

      // 自动展开所有节点（可选）
      this.$nextTick(() => {
        const tree = this.$refs.tree;
        if (tree) {
          tree.setCurrentKey(null);
          tree.store.nodesMap = {};
          tree.store.root.setData(this.tableData);
        }
      });
    },
    clearDataAndHideDialog() {
      this.form = {};
      this.visibleDialog = false;
    },
  },
});
